﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SSN.Utilities.Database;

namespace SSN.WebFramework.Logging
{
    public static class LoggingManager
    {
        /// <summary>
        /// The database table to log entries to.
        /// </summary>
        public static string LogTableName { get { return WebSettings.LoggingDbTable; } }
        public static string LogDetailsTableName { get { return WebSettings.LoggingDbTable; } }

        /// <summary>
        /// Adds a log entry to the the logging table.
        /// </summary>
        /// <param name="entry">Info about the log entry.</param>
        public static void AddEntry(LogEntry entry)
        {
            int id = DbManager.BossDb.ExecuteCommandFormat(@"INSERT INTO {0}(timestamp,userid,url,page,ip,server,browser,os,site) VALUES(GETDATE(),'{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');SELECT SCOPE_IDENTITY();",
                                                             LogTableName,
                                                             entry.UserID,
                                                             entry.RawURL,
                                                             entry.PageURL,
                                                             entry.UserIP,
                                                             entry.Server,
                                                             entry.BrowserCode,
                                                             entry.OSCode,
                                                             WebSettings.AppName);

            if(id > 0){
                
                foreach (string s in entry.Parameters.Keys)
                {
                    DbManager.BossDb.ExecuteCommandFormat(@"INSERT INTO {0}(log_id,param_name,param_value) VALUES({1},'{2}','{3}')", LogDetailsTableName, id, s, entry.Parameters[s]);
                }
            }
        }
    }
}
